package com.hmkx.solr.query;


import org.apache.lucene.document.Document;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.SortedDocValues;
import org.apache.lucene.queries.CustomScoreProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author hht
 * @Description 定义Provider，Parser 提供给计算评分的时候调用
 * 源码如下：
 * CustomScoreQuery 类的 score方法
 * return this.qWeight * this.provider.customScore(this.subQueryScorer.docID(), this.subQueryScorer.score(), this.vScores);
 * @Date 14:26 2019/7/24
 * @Param 
 * @return 
 **/
public class HmkxProvider extends CustomScoreProvider {
    final static Logger log= LoggerFactory.getLogger(HmkxProvider.class);
    private SortedDocValues titleValues;

    public HmkxProvider(LeafReaderContext context) {
        super(context);
    }

    @Override
    public float customScore(int doc, float subQueryScore, float valSrcScore) throws IOException {
        float myScore = 1f;
        //补充额外的业务逻辑  可以获取doc中的某个字段，这里获取的是发布时间
        LeafReader lr = context.reader();
        Date pubDate = new Date(lr.getNumericDocValues("pubdate").get(doc));
        String t = lr.terms("title").toString();
        Document document = lr.document(doc);
        log.error("tttttttttttttttttttt"+t);
        log.error("ssssssssssssssssssssss"+document.get("title"));

        int diffMonth = getMonthDiff(new Date(),pubDate);
//        log.error("id:"+doc+",pudate:"+pubDate);
//        log.error("月份查:"+diffMonth);
        myScore = myScore-(diffMonth*0.05f);
        if(myScore>1){
            myScore = 1;
        }else if(myScore<0.5){
            myScore = 0.5f;
        }
//        log.error("时间系数:"+myScore);
        return  subQueryScore*valSrcScore *myScore;
    }

    /**
     *  获取两个日期相差的月数
     * @param d1    较大的日期
     * @param d2    较小的日期
     * @return  如果d1>d2返回 月数差 否则返回0
     */
    public static int getMonthDiff(Date d1, Date d2) {
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(d1);
        c2.setTime(d2);
        if(c1.getTimeInMillis() < c2.getTimeInMillis()) return 0;
        int year1 = c1.get(Calendar.YEAR);
        int year2 = c2.get(Calendar.YEAR);
        int month1 = c1.get(Calendar.MONTH);
        int month2 = c2.get(Calendar.MONTH);
        int day1 = c1.get(Calendar.DAY_OF_MONTH);
        int day2 = c2.get(Calendar.DAY_OF_MONTH);
        // 获取年的差值 假设 d1 = 2015-8-16  d2 = 2011-9-30
        int yearInterval = year1 - year2;
        // 如果 d1的 月-日 小于 d2的 月-日 那么 yearInterval-- 这样就得到了相差的年数
        if(month1 < month2 || month1 == month2 && day1 < day2) yearInterval --;
        // 获取月数差值
        int monthInterval =  (month1 + 12) - month2  ;
        if(day1 < day2) monthInterval --;
        monthInterval %= 12;
        return yearInterval * 12 + monthInterval;
    }

}
